package com.entities;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dstats.Constants;
import com.fetch.FetchHeroes;

public class Hero {
	public static List<Hero> heroes;
	private int id;
	private String name;
	private String localized_name;
	private static final String npc_dota_hero = "npc_dota_hero_"; 
	private static final String HEROES = "heroes";
	public static final String url_imgs = "http://cdn.dota2.com/apps/dota2/images/heroes/";
	private static final String HeroPediaUrl = "http://www.dota2.com/hero/";
	private static final String endUrl = "_lg";
	
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public String getLocalized_name() {
		return localized_name;
	}
	
	Hero(int id, String name, String localized_name){
		this.id = id;
		this.name = name;
		this.localized_name = localized_name;
	
		
	}
	
	public static Hero getHeroById(String language, int id){
		for(Hero h: getHeroes(language)){
			if(h.getId()==id){
				return h;
			}
		}
		return null;
	}

	public static List<Hero> getHeroes(String language){
		if(heroes==null){
		try {

				JSONObject json = new FetchHeroes(language).execute().get();
			return getHeroes(json);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
			}
		}
		return heroes;
		}

	
	public static List<Hero> getHeroes(JSONObject json){

		heroes = new ArrayList<Hero>();
	try {
		JSONArray jaHeroes = json.getJSONObject(Constants.RESULT).getJSONArray(HEROES);
		for(int cont = 0; cont<jaHeroes.length(); cont++){
			JSONObject joHero = jaHeroes.getJSONObject(cont);
			heroes.add(new Hero(joHero.getInt("id"), joHero.getString("name"), joHero.getString("localized_name")));
			
		}
		class NameComparator implements Comparator<Hero> {
		    public int compare(Hero hero, Hero otherHero) {
		        return hero.getLocalized_name().
		                compareTo(otherHero.getLocalized_name());
		    }
		}
		
		NameComparator comparator =new NameComparator();
		Collections.sort(heroes, comparator);

		} catch (JSONException e) {
			e.printStackTrace();
		}
	
	return heroes;	
	}
	

	
	public String getHeropediaUrl(){
		return HeroPediaUrl + localized_name.replaceAll(" ", "_");
		
	}
	
	public String getImgLgUrl() {
		return url_imgs+getImgLgUrl();
	}
	
	public String getImgResString() {
		return 	name.replaceAll(npc_dota_hero, "")+endUrl;
	}
	
}

